<template>
  <div>
    <el-card>
      <el-table class="category-list " :data="category1" style="width:90%; margin-bottom:20px;" :row-key="getKey" border lazy :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :row-class-name="tableRowClassName">
        <el-table-column prop="date" label="分类ID" width="150" align="center">
        </el-table-column>
        <el-table-column prop="name" label="分类名称">
        </el-table-column>
        <el-table-column prop="address" width="250" align="center">
          <template slot="header" slot-scope="scope">
            <el-input v-model="search" size="mini" placeholder="按Enter键添加一级分类" />
          </template>
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-plus"></el-button>
            <el-button type="primary" size="mini" icon="el-icon-edit-outline"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'Category',
  data() {
    return {
      search: '',
    }
  },
  methods: {
    ...mapActions('category', ['getCategoryList1', 'getCategoryList2', 'getCategoryList3']),
    async load(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve);
      if (tree.level === 1) {//获取二级分类的数据
        const res = await this.getCategoryList2(tree.id)
        if (res === 'ok') {
          let category2 = this.categoryList2
          if (category2 && category2.length > 0) {
            category2.forEach(item => {
              // 标识有子分类
              item.hasChildren = true
              // 分类级别为2级
              item.level = 2
            })
          } else {
            row.hasChildren = false
            category2 = []
          }
          resolve(category2)
        }
      }
      if (tree.level === 2) {
        const res = await this.getCategoryList3(tree.id)
        if (res === 'ok') {
          let category3 = this.categoryList3
          if (category3 && category3.length > 0) {
            resolve(category3)
          } else {
            row.hasChildren = false
            category3 = []
            resolve(category3)
          }
        }
      }
      
    },
    // 获取唯一id给key
    getKey(row) {
      return row.level + '_' + row.id
    },
    tableRowClassName({ row }) {
      if (row.level === 2) {
        return 'level2-row'
      }
    }
  },
  mounted() {
    this.getCategoryList1()
  },
  computed: {
    ...mapState('category', ['categoryList1', 'categoryList2', 'categoryList3']),
    category1() {
      return this.categoryList1.map(item => {
        item.hasChildren = true
        item.level = 1
        return item
      })
    }
  }
}
</script>

<style lang="scss">
.category-list {
  .level2-row {
    background-color: #F2F9EC;
  }
}
</style>
